package org.domain.demo.session.user;

import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;

import org.domain.demo.dao.UsersDAO;
import org.domain.demo.entity.Users;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.FlushModeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.End;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.international.StatusMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.log.Log;

@Stateful
@Name("userMaintain")
public class UserMaintainBean implements UserMaintain
{
    @Logger private Log log;
    
	@In
	private StatusMessages statusMessages;

    @In(value = "entityManager")
	private EntityManager em;
	
	@Out
	@In(create = true, required = false)
	private Users usersEO;
	
	@In(create = true)
	private UsersDAO usersDAO;
	
	@Out
	private boolean initUser;
	
	@RequestParameter
	private Integer userId;
	
	private UserValidator userValidator;
	
	@Begin(join = true, flushMode = FlushModeType.MANUAL)
	public String initUserMaintain() {
		if(userId == null){
			initUser = true;
			usersEO = new Users();
		}else{
			initUser = false;
			usersEO = em.find(Users.class, userId);
		}
		return "";
	}
	
	@End
	public String saveUser() {
		if(!getUserValidator().valitateUser(em, usersEO))
		{
			return null;
		}
		em.merge(usersEO);
		em.flush();
		statusMessages.addFromResourceBundle(Severity.INFO,"user.save.successful",usersEO.getFullName());
		return "success";
	}
	
	private UserValidator getUserValidator() {
		if (this.userValidator == null) {
			userValidator = new UserValidator(statusMessages,usersDAO);
		}
		return userValidator;
	}
	
	
	@Destroy
	@Remove
	public void destroy() {}

}
